<template>
	<view class="pc-container">
		<!-- 群主信息：添加v-if确保数据加载后渲染 -->
		<view class="form-section" v-if="isOwnDataLoaded">
			<h2 class="section-title">👤 群主信息</h2>
			
			<!-- 修正uni-table结构：添加uni-table-body -->
			<uni-table class="form-table">
				<uni-table-body>
					<!-- 头像行 -->
					<uni-tr>
						<uni-td colspan="2" class="avatar-cell">
							<view class="avatar-upload" @click="uploadAvatar">
								<image v-if="own.photo" :src="own.photo" class="avatar-image" />
								<view v-else class="upload-hint">
									<uni-icons type="plus" size="28" color="#666" />
									<text>上传头像</text>
								</view>
							</view>
						</uni-td>
					</uni-tr>

					<!-- 基本信息 -->
					<uni-tr>
						<uni-td class="label">姓名：</uni-td>
						<uni-td>
							<input class="form-input" v-model="own.name" placeholder="请输入姓名" />
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">性别：</uni-td>
						<uni-td>
							<view class="gender-select">
								<text 
									v-for="item in genderOptions" 
									:key="item.value" 
									:class="['gender-item', { active: own.sex === item.value }]" 
									@click="own.sex = item.value"
								>
									{{ item.label }}
								</text>
							</view>
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">年龄：</uni-td>
						<uni-td>
							<!-- 修正v-model类型：移除.number，统一用字符串 -->
							<input class="form-input" v-model="own.age" type="number" placeholder="18-65岁" style="width: 200px" />
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">联系电话：</uni-td>
						<uni-td>
							<input class="form-input" v-model="own.telphone" type="tel" placeholder="请输入手机号" style="width: 300px" />
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">营业地址：</uni-td>
						<uni-td>
							<input class="form-input" v-model="own.address" placeholder="详细地址" style="width: 100%" />
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">服务理念：</uni-td>
						<uni-td>
							<textarea class="form-textarea" v-model="own.signature" placeholder="请输入服务理念..." style="width: 100%; height: 80px" />
						</uni-td>
					</uni-tr>
				</uni-table-body>
			</uni-table>
		</view>

		<!-- 群信息：同样修正结构 -->
		<view class="form-section" v-if="isGroupDataLoaded">
			<h2 class="section-title">👥 群信息</h2>
			<uni-table class="form-table">
				<uni-table-body>
					<uni-tr>
						<uni-td class="label">群名称：</uni-td>
						<uni-td>
							<input class="form-input" v-model="groupInfo.groupName" placeholder="请输入群名称" style="width: 100%" />
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">服务范围：</uni-td>
						<uni-td>
							<view class="location-cell" @click="navToLocationPicker(group)">
								<text v-if="groupInfo.location">{{ groupInfo.location.address }}</text>
								<text v-else class="placeholder">点击设置服务范围</text>
								<uni-icons type="location" size="18" color="#666" />
							</view>
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">群标志：</uni-td>
						<uni-td>
							<view class="upload-wrap" @click="uploadGroupImage">
								<image v-if="groupInfo.groupPicPath" :src="groupInfo.groupPicPath" class="group-image" />
								<text v-else class="upload-text">点击上传图片</text>
							</view>
						</uni-td>
					</uni-tr>

					<uni-tr>
						<uni-td class="label">群口号：</uni-td>
						<uni-td>
							<textarea class="form-textarea" v-model="groupInfo.signature" placeholder="请输入群口号..." style="width: 100%; height: 80px" />
						</uni-td>
					</uni-tr>
				</uni-table-body>
			</uni-table>
		</view>

		<!-- 操作按钮：数据加载完成才显示 -->
		<view class="action-bar" v-if="isOwnDataLoaded && isGroupDataLoaded">
			<button class="submit-btn" @click="formSubmit">提交修改</button>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
export default {
	data() {
		return {
			group: {}, // 修正初始值：从数组改为对象（数据库返回单条数据）
			genderOptions: [
				{ label: '♂ 男', value: 'male' },
				{ label: '♀ 女', value: 'female' }
			],
			submitting: false,
			isOwnDataLoaded: false, // 新增：群主数据加载状态
			isGroupDataLoaded: false, // 新增：群数据加载状态
			own: {
				// 优化：给所有属性添加非空初始值，避免渲染时undefined
				name: '',
				photo: '',
				signature: '',
				sex: 'male', // 性别默认值（避免无选中态）
				age: '',
				address: '',
				telphone: '',
				ownLocation: null
			},
			groupInfo: {
				groupName: '',
				location: null,
				radius: 1000,
				groupPicPath: '',
				signature: '',
				aMapLocation: []
			}
		};
	},
	onLoad(res) {
		// 校验参数：避免ID缺失导致请求失败
		if (!res.ID) {
			uni.showToast({ title: '缺少群ID参数', icon: 'none' });
			return;
		}
		this.getGroup(res.ID);
	},
	methods: {
		async getGroup(id) {
			try {
				const groupRes = await db
					.collection('Group')
					.where({ _id: id })
					.get();

				// 校验数据库返回结果
				if (!groupRes.data || groupRes.data.length === 0) {
					throw new Error('未查询到群信息');
				}
				const groupData = groupRes.data[0];

				// 1. 赋值群信息（深拷贝，避免直接修改原数据）
				this.group = JSON.parse(JSON.stringify(groupData));
				this.groupInfo = {
					groupName: groupData.groupName || '',
					location: groupData.location || null,
					radius: groupData.radius || 1000,
					groupPicPath: groupData.groupPicPath || '',
					signature: groupData.signature || '',
					aMapLocation: groupData.aMapLocation || [],
					status:groupData.status
				};

				// 2. 赋值群主信息（处理后端可能返回的空值）
				const ownData = groupData.ownInfo || {};
				this.own = {
					name: ownData.name || '',
					photo: ownData.avatarUrl || '',
					signature: ownData.signature || '',
					sex: ownData.sex || 'male',
					age: ownData.age ? ownData.age.toString() : '', // 转为字符串，匹配input
					address: ownData.address || '',
					telphone: ownData.telphone || '',
					ownLocation: ownData.ownLocation || null
				};

				// 3. 标记数据加载完成，触发渲染
				this.isOwnDataLoaded = true;
				this.isGroupDataLoaded = true;

			} catch (e) {
				console.error('获取群信息失败:', e.message);
				uni.showToast({ title: `加载失败: ${e.message}`, icon: 'none' });
			}
		},

		// 上传头像
		uploadAvatar() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album'],
				success: (res) => {
					this.own.photo = res.tempFilePaths[0];
				},
				fail: (err) => {
					console.error('选择头像失败:', err);
					uni.showToast({ title: '选择图片失败', icon: 'none' });
				}
			});
		},

		// 上传群图片
		uploadGroupImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album'],
				success: (res) => {
					this.groupInfo.groupPicPath = res.tempFilePaths[0];
				},
				fail: (err) => {
					console.error('选择群图片失败:', err);
					uni.showToast({ title: '选择图片失败', icon: 'none' });
				}
			});
		},

		// 跳转位置选择
		navToLocationPicker(group) {
			if (!group._id) {
				uni.showToast({ title: '群信息未加载完成', icon: 'none' });
				return;
			}
			try {
				const formatGroup = encodeURIComponent(JSON.stringify(group));
				uni.navigateTo({
					url: `/own/map/map?data=${formatGroup}`,
					fail: (err) => {
						console.error('跳转位置选择失败:', err);
						uni.showToast({ title: '页面跳转失败', icon: 'none' });
					}
				});
			} catch (e) {
				console.error('序列化群信息失败:', e);
				uni.showToast({ title: '数据处理失败', icon: 'none' });
			}
		},

		// 表单提交
		async formSubmit() {
			if (this.submitting) return;
			this.submitting = true;

			// 表单验证
			if (!this.validateForm()) {
				this.submitting = false;
				return;
			}

			try {
				// 优化：仅上传有变化的图片（避免空文件上传）
				const uploadTasks = [];
				// 群图片上传（仅当有临时路径时）
				if (this.groupInfo.groupPicPath && this.groupInfo.groupPicPath.includes('tmp')) {
					uploadTasks.push(this.uploadFile({
						filePath: this.groupInfo.groupPicPath,
						type: 'groupPic'
					}));
				} else {
					uploadTasks.push(Promise.resolve(this.groupInfo.groupPicPath)); // 无变化则直接传原路径
				}
				// 头像上传（仅当有临时路径时）
				if (this.own.photo && this.own.photo.includes('tmp')) {
					uploadTasks.push(this.uploadFile({
						filePath: this.own.photo,
						type: 'ownPic'
					}));
				} else {
					uploadTasks.push(Promise.resolve(this.own.photo)); // 无变化则直接传原路径
				}

				// 并行执行上传
				const [groupPicRes, ownPicRes] = await Promise.all(uploadTasks);

				// 构造提交数据（仅包含需要更新的字段）
				const submitData = {
					own: { ...this.own, photo: ownPicRes },
					groupName: this.groupInfo.groupName,
					location: this.groupInfo.location,
					groupPicPath: groupPicRes,
					signature: this.groupInfo.signature,
					radius: this.groupInfo.radius,
					aMapLocation: this.groupInfo.aMapLocation
				};

				// 提交到数据库
				const updateRes = await db
					.collection('Group')
					.where({ _id: this.group._id })
					.update(submitData);

				// 优化：提示逻辑（避免重复弹窗）
				uni.showModal({
					title: '修改成功',
					content: `群名称：${submitData.groupName}`,
					confirmText: '去设置区域',
					cancelText: '返回',
					success: (res) => {
						if (res.confirm) {
							this.navToLocationPicker(this.group);
						} else {
							uni.navigateBack();
						}
					}
				});

			} catch (error) {
				console.error('提交失败:', error);
				uni.showToast({
					title: `提交失败: ${error.message || '未知错误'}`,
					icon: 'none',
					duration: 3000
				});
			} finally {
				this.submitting = false;
			}
		},

		// 封装的上传方法（增加错误处理）
		async uploadFile({ filePath, type }) {
			if (!filePath) throw new Error(`请先选择${type === 'groupPic' ? '群图片' : '头像'}`);

			uni.showLoading({ title: `${type === 'groupPic' ? '群图片' : '头像'}上传中...`, mask: true });
			try {
				// 上传文件到云存储
				const uploadRes = await uniCloud.uploadFile({
					cloudPath: `${type}/${Date.now()}_${Math.random().toString(36).slice(2, 10)}.jpg`, // 优化文件名唯一性
					filePath,
					timeout: 30000 // 增加超时时间
				});

				// 校验上传结果
				if (!uploadRes.fileID) throw new Error('上传文件未返回fileID');

				// 获取临时访问地址
				const tempRes = await uniCloud.getTempFileURL({
					fileList: [uploadRes.fileID]
				});

				if (!tempRes.fileList || tempRes.fileList.length === 0) throw new Error('获取临时URL失败');
				return tempRes.fileList[0].tempFileURL;

			} catch (error) {
				console.error(`${type}上传失败:`, error);
				throw new Error(`${type === 'groupPic' ? '群图片' : '头像'}上传失败`);
			} finally {
				uni.hideLoading();
			}
		},

		// 表单验证（优化逻辑，避免重复判断）
		validateForm() {
			// 年龄转数字（统一验证）
			const ageNum = Number(this.own.age);

			const validations = [
				{ check: this.own.name.trim(), msg: '请填写姓名' },
				{ check: this.groupInfo.groupName.trim(), msg: '请填写群名称' },
				{ check: this.own.telphone.trim(), msg: '请填写联系电话' },
				{ check: /^1[3-9]\d{9}$/.test(this.own.telphone.trim()), msg: '手机号格式错误' },
				{ check: !isNaN(ageNum) && ageNum >= 18 && ageNum <= 65, msg: '年龄需在18-65周岁之间' }
			];

			// 遍历验证
			for (const { check, msg } of validations) {
				if (!check) {
					uni.showToast({ title: msg, icon: 'none', duration: 2000 });
					return false;
				}
			}
			return true;
		}
	}
};
</script>

<style lang="scss" scoped>
.pc-container {
	max-width: 1000px;
	margin: 20px auto;
	padding: 24px;
	background: #fff;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-section {
	margin-bottom: 40px;

	.section-title {
		font-size: 20px;
		color: #333;
		margin-bottom: 20px;
		padding-bottom: 10px;
		border-bottom: 2px solid #eee;
	}
}

.form-table {
	width: 100%;
	border-collapse: collapse;

	uni-tr {
		border-bottom: 1px solid #eee;

		&:last-child {
			border-bottom: none;
		}
	}

	uni-td {
		padding: 16px;
		vertical-align: top;

		&.label {
			width: 120px;
			text-align: right;
			color: #666;
			font-weight: 500;
			padding-right: 24px;
		}
	}
}

/* 头像上传 */
.avatar-cell {
	text-align: center;
	padding: 24px 0 !important;

	.avatar-upload {
		display: inline-block;
		width: 120px;
		height: 120px;
		border: 2px dashed #ddd;
		border-radius: 50%;
		cursor: pointer;
		transition: all 0.3s;

		&:hover {
			border-color: #2196f3;
			background: #f5faff;
		}

		.avatar-image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
			object-fit: cover;
		}

		.upload-hint {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100%;
			color: #999;
			font-size: 12px;
		}
	}
}

/* 性别选择 */
.gender-select {
	display: flex;
	gap: 12px;

	.gender-item {
		padding: 8px 20px;
		border: 1px solid #ddd;
		border-radius: 4px;
		cursor: pointer;
		transition: all 0.2s;

		&:hover {
			border-color: #2196f3;
			color: #2196f3;
		}

		&.active {
			background: #2196f3;
			color: white;
			border-color: #2196f3;
		}
	}
}

/* 位置选择 */
.location-cell {
	display: flex;
	align-items: center;
	gap: 8px;
	cursor: pointer;
	padding: 8px 12px;
	border: 1px solid #ddd;
	border-radius: 4px;
	transition: all 0.2s;

	&:hover {
		border-color: #2196f3;
		background: #f5faff;

		.placeholder {
			color: #2196f3;
		}
	}

	.placeholder {
		color: #999;
	}
}

/* 图片上传 */
.upload-wrap {
	width: 200px;
	height: 120px;
	border: 2px dashed #ddd;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s;
	overflow: hidden;

	&:hover {
		border-color: #2196f3;
		background: #f5faff;
	}

	.group-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-text {
		color: #999;
		font-size: 12px;
	}
}

/* 按钮样式 */
.action-bar {
	text-align: center;
	margin-top: 40px;

	.submit-btn {
		width: 200px;
		height: 40px;
		background: #2196f3;
		color: white;
		border: none;
		border-radius: 20px;
		cursor: pointer;
		transition: all 0.2s;

		&:hover {
			background: #1a73e8;
			transform: translateY(-1px);
			box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
		}
	}
}

/* 通用输入样式 */
.form-input {
	padding: 8px 12px;
	border: 1px solid #ddd;
	border-radius: 4px;
	transition: all 0.2s;
	width: 100%; // 统一宽度，避免部分input宽度异常

	&:focus {
		border-color: #2196f3;
		box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
		outline: none;
	}
}

.form-textarea {
	padding: 12px;
	border: 1px solid #ddd;
	border-radius: 4px;
	resize: vertical;
	min-height: 80px;
	line-height: 1.5;
	width: 100%; // 统一宽度
}
</style>